import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.dart';
import 'package:toast/toast.dart';

import 'news_channel.dart';
import 'news_json_resp.dart';
import 'news_list.dart';


/**
 * 头条新闻
 */
class NewList extends StatefulWidget{
  @override
  _NewListState createState() => _NewListState();
}

class _NewListState extends State<NewList> with SingleTickerProviderStateMixin{
  
  List<ChannelList> _channelList;
  NewsData _newsData;
  String defaultUrl="https://v.juhe.cn/toutiao/index?";// 使用http会导致访问不安全而请求失败
  String key="key=b315c04b6387c68b4199f8f9b219e83b";// 访问新闻接口的唯一key
  String type="type=";// 访问新闻接口时指定新闻类型（头条、军事、科技...）
  String page="page=";// 访问新闻接口时指定页数（接口可提供30页，默认为1）
  String url;// 将上述信息合并为一个完整的接口地址
  ChannelList currentChannel;

  bool isLoading= false;
  List<Widget>  listItems;

  @override
  Widget build(BuildContext context) {
    addChannelList();

    final popupMenuEntry = <PopupMenuEntry<String>>[
      MyPopupMenuItem(null, null, '0', '今日头条'),
      MyPopupMenuItem(null, null, '1', '社会民生'),
    ];

    final channelButton = FloatingActionButton(
      tooltip: "刷新",
      child: PopupMenuButton<String>(
        icon: Icon(Icons.change_history),
        tooltip: "切换频道",
        offset: Offset(0,-90),//调节弹出菜单的相对位置
        onSelected: (value){
          currentChannel = _channelList[int.parse(value)];
          refresh();
        },
        itemBuilder: (context) {
          return popupMenuEntry;
        },
        enableFeedback: true,
      ),
    );

    return Scaffold(
      body: Center(
        child: listItems !=null ?
        AnimationLimiter(
            child: ListView.builder(
                itemCount: listItems.length,
                itemBuilder: (context ,index){
                  return listItems[index];
                }
            )
        ) : Text("请用右下角切换频道"),

      ),
      floatingActionButton: channelButton,
    );
  }

  addChannelList(){
    _channelList=new List();
    _channelList.add(new ChannelList("top", "头条"));
    _channelList.add(new ChannelList("shehui", "社会"));
    currentChannel=_channelList[0];
  }

  //获取新闻、切换新闻类型后刷新数据
  refresh() async{
    url="$defaultUrl$type${currentChannel.type}&$key";
    debugPrint("url:$url");
    if(!isLoading){
      isLoading = true;
      try{
        HttpClient httpClient = new HttpClient();
        HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));
        HttpClientResponse response = await request.close();
        String responseContent = await response.transform(utf8.decoder).join();
        _newsData = NewsData.fromJson(json.decode(responseContent));
        listItems = ListBuilder.genWidgesFromJson(_newsData, context);
        int listItemsSize=listItems.length;
        debugPrint("listItemsSize:$listItemsSize");
        setState(() {});
        httpClient.close();
      } catch (e){
        debugPrint("请求失败：$e");
        Toast.show("获取新闻数据失败", context);
      }finally {
        setState(() {
          isLoading = false;
        });
      }
    }else{
      debugPrint("正在刷新");
    }
  }

}

//自定义一个弹出菜单项
Widget MyPopupMenuItem(IconData icon,Color iconColor,String value,String text) {
  return PopupMenuItem<String>(
    value: value,
    child: Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(icon, color: iconColor, ),
        Text("   " + text),
      ],
    ),
  );
}